<?php

namespace app\common\library;

use app\common\exception\UploadException;
use app\admin\model\SubjectAttachment;
use Exception;
use fast\Random;
use FilesystemIterator;
use think\Config;
use think\File;
use think\Hook;

class Remote
{

    protected $config = [];

    protected $error = '';

    protected $fileInfo = null;

    public function __construct($file = null)
    {
        $this->config = Config::get('upload');
        // exit(print_r($this->config));
    }

    /**
     * 获取存储的文件名
     * @param string $savekey  保存路径
     * @param string $filename 文件名
     * @param string $md5      文件MD5
     * @param string $category 分类
     * @return mixed|null
     */
    public function getSavekey($url, $savekey = null, $filename = null, $md5 = null, $category = null)
    {
        $suffix = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        $filename = xss_clean(strip_tags(htmlspecialchars($filename)));
        $fileprefix = substr($filename, 0, strripos($filename, '.'));
        $md5 = md5($url);
        $category = $category ? xss_clean($category) : 'all';
        $replaceArr = [
            '{year}'       => date("Y"),
            '{mon}'        => date("m"),
            '{day}'        => date("d"),
            '{hour}'       => date("H"),
            '{min}'        => date("i"),
            '{sec}'        => date("s"),
            '{random}'     => Random::alnum(16),
            '{random32}'   => Random::alnum(32),
            '{category}'   => $category ? $category : '',
            '{filename}'   => substr($filename, 0, 100),
            '{fileprefix}' => substr($fileprefix, 0, 100),
            '{suffix}'     => $suffix,
            '{.suffix}'    => $suffix ? '.' . $suffix : '',
            '{filemd5}'    => $md5,
        ];
        $savekey = $savekey ? $savekey : $this->config['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        return $savekey;
    }

    public function fileSave($url, $category = "")
    {
        // 获取后戳
        $suffix = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        // exit($suffix);

        $filename_old = substr($url, strripos($url, "/") + 1);
        // exit($filename_old);
        $fileprefix = substr($filename_old, 0, strripos($filename_old, '.'));
        // exit($fileprefix);

        $md5 = md5($url);
        // exit($md5);

        $savekey = $this->getSavekey($url, null, $filename_old, null, null);
        // exit($savekey);

        $ch = curl_init();
        $timeout = 60;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        $file_content = curl_exec($ch);
        curl_close($ch);

        //保存目录
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        // exit($uploadDir);

        //新文件名
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        // exit($fileName);

        // 保存路径
        $save_dir = ROOT_PATH . 'public' . $uploadDir;

        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return false;
        }

        //绝对路径
        $file_path = $save_dir . $fileName;

        $fp2 = @fopen($file_path, 'a');
        fwrite($fp2, $file_content);
        fclose($fp2);

        // 创建一个fileinfo资源
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        // 获取文件的MIME类型
        $mimeType = finfo_file($finfo,  $file_path);
        // 关闭fileinfo资源
        finfo_close($finfo);
        // 输出MIME类型
        // exit($mimeType);

        //文件大小
        $filesize = filesize($file_path);

        //加密串
        $sha1 = sha1_file($file_path);

        $imgInfo = null;
        $imagewidth = 0;
        $imageheight = 0;
        //验证是否为图片文件
        if (in_array($mimeType, ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
            $imgInfo = getimagesize($save_dir . $fileName);
            $imagewidth = $imgInfo[0];
            $imageheight = $imgInfo[1];
        }
        $auth = Auth::instance();
        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            'filename'    => mb_substr(htmlspecialchars(strip_tags($filename_old)), 0, 100),
            'category'    => $category,
            'filesize'    => $filesize,
            'imagewidth'  =>  $imagewidth,
            'imageheight' =>  $imageheight,
            'imagetype'   => $suffix,
            'imageframes' => 0,
            'mimetype'    => $mimeType,
            'url'         => $uploadDir . $fileName,
            'uploadtime'  => time(),
            'storage'     => 'local',
            'sha1'        => $sha1,
            'extparam'    => '',
            'show_position' => '',
        );

        // exit(print_r($params));

        $attachment = new SubjectAttachment();
        $attachment->data(array_filter($params));
        $attachment->save();

        return $attachment;
    }

    /**
     * 只记录，不获取文件具体信息
     */
    public function fileSaveRecord($url)
    {
        // 获取后戳
        $suffix = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        // exit($suffix);

        $filename_old = substr($url, strripos($url, "/") + 1);
        // exit($filename_old);
        $fileprefix = substr($filename_old, 0, strripos($filename_old, '.'));
        // exit($fileprefix);

        $md5 = md5($url);
        // exit($md5);

        $mimeType = "";
        //图片类型
        if (in_array($suffix, ["jpeg", "jpg"])) {
            $mimeType = "image/jpeg";
        }
        if (in_array($suffix, ["png"])) {
            $mimeType = "image/png";
        }
        if (in_array($suffix, ["gif"])) {
            $mimeType = "image/gif";
        }
        //pdf类型
        if (in_array($suffix, ["pdf"])) {
            $mimeType = "application/pdf";
        }
        //office类型
        if (in_array($suffix, ["doc"])) {
            $mimeType = "application/msword";
        }
        if (in_array($suffix, ["docx"])) {
            $mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }
        if (in_array($suffix, ["pptx"])) {
            $mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        }
        //多媒体类型
        if (in_array($suffix, ["mp4"])) {
            $mimeType = "video/mp4";
        }

        // exit($mimeType);

        $headers = get_headers($url, true);
        // exit(print_r($headers));
        if(!$headers || !isset($headers['Content-Length'])){
            throw Exception("获取远程文件出现异常");
        }
        $filesize = $headers['Content-Length'];

        // $filesize=filesize($url);

        // exit($filesize."");

        //加密串
        $sha1 = "";

        $imgInfo = null;
        $imagewidth = 0;
        $imageheight = 0;

        $auth = Auth::instance();

        //获取unique_id
        $unique_id = "";
        $id_info = db("unique_id")->where("type", 2)->where("status", 0)->orderRaw("rand()")->find();
        if ($id_info) {
            $unique_id = $id_info["unique_id"];
            db("unique_id")->where("id", $id_info["id"])->update([
                "status" => 1,
                "updatetime" => time(),
            ]);
        }

        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            'filename'    => mb_substr(htmlspecialchars(strip_tags($filename_old)), 0, 100),
            'filesize'    => $filesize,
            'imagewidth'  =>  $imagewidth,
            'imageheight' =>  $imageheight,
            'imagetype'   => $suffix,
            'imageframes' => 0,
            'mimetype'    => $mimeType,
            'url'         => $url,
            'uploadtime'  => time(),
            'storage'     => 'remote',
            'sha1'        => $sha1,
            "createtime" => time(),
            "updatetime" => time(),
            "uploadtime" => time(),
            "unique_id" => $unique_id,
        );

        // exit(print_r($params));

        $attachment_id = db("subject_attachment")->insertGetId($params);

        return $attachment_id;
    }

     /**
     * 从旧数据复制部分数据
     */
    public function fileSaveCopy($url,$attachment)
    {
        // 获取后戳
        $suffix = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        // exit($suffix);

        // $filename_old = substr($url, strripos($url, "/") + 1);
        $filename_old=$attachment["filename"];
        // exit($filename_old);
        $fileprefix = substr($filename_old, 0, strripos($filename_old, '.'));
        // exit($fileprefix);

        $md5 = md5($url);
        // exit($md5);

        $mimeType = "";
        //图片类型
        if (in_array($suffix, ["jpeg", "jpg"])) {
            $mimeType = "image/jpeg";
        }
        if (in_array($suffix, ["png"])) {
            $mimeType = "image/png";
        }
        if (in_array($suffix, ["gif"])) {
            $mimeType = "image/gif";
        }
        //pdf类型
        if (in_array($suffix, ["pdf"])) {
            $mimeType = "application/pdf";
        }
        //office类型
        if (in_array($suffix, ["doc"])) {
            $mimeType = "application/msword";
        }
        if (in_array($suffix, ["docx"])) {
            $mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }
        if (in_array($suffix, ["pptx"])) {
            $mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        }
        //多媒体类型
        if (in_array($suffix, ["mp4"])) {
            $mimeType = "video/mp4";
        }

        // exit($mimeType);

        $headers = get_headers($url, true);
        $filesize = $headers['Content-Length'];

        // $filesize=filesize($url);

        // exit($filesize."");

        //加密串
        $sha1 = "";

        $imgInfo = null;
        $imagewidth = 0;
        $imageheight = 0;

        $auth = Auth::instance();

        //获取unique_id
        $unique_id = "";
        $id_info = db("unique_id")->where("type", 2)->where("status", 0)->orderRaw("rand()")->find();
        if ($id_info) {
            $unique_id = $id_info["unique_id"];
            db("unique_id")->where("id", $id_info["id"])->update([
                "status" => 1,
                "updatetime" => time(),
            ]);
        }

        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            'filename'    => mb_substr(htmlspecialchars(strip_tags($filename_old)), 0, 100),
            'filesize'    => $filesize,
            'imagewidth'  =>  $imagewidth,
            'imageheight' =>  $imageheight,
            'imagetype'   => $suffix,
            'imageframes' => 0,
            'mimetype'    => $mimeType,
            'url'         => $url,
            'uploadtime'  => time(),
            'storage'     => 'remote',
            'sha1'        => $sha1,
            "createtime" => time(),
            "updatetime" => time(),
            "uploadtime" => time(),
            "unique_id" => $unique_id,
        );

        // exit(print_r($params));

        $attachment_id = db("subject_attachment")->insertGetId($params);

        //插入扩展表
        $ext = [
            "attachment_id" => $attachment_id,
        ];
        db("subject_attachment_ext")->insert($ext);


        return $attachment_id;
    }
}
